# Create your views here.
from scuiapply.models import User,Menu,Post
import datetime, jwt, json
from django.conf import settings
from django.http import JsonResponse
from django.views import View
from .serializer import *
from rest_framework.viewsets import ModelViewSet
from rest_framework.decorators import action

#登录
class Login(View):
    def post(self, request):
        params = json.loads(request.body)
        userModel = User.objects.get(user=params.get('user'), password=params.get('password'))
        result = {}
        if userModel is not None:
            headers = {
                'typ': 'jwt',
                'alg': 'HS256'
            }
            # 构造payload
            payload = {
                'user': userModel.user,  # 自定义用户名
                'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=5)  # 超时时间
            }
            data = {}
            token = jwt.encode(payload=payload, key=settings.SECRET_KEY,
                               algorithm="HS256", headers=headers)
            result['massage'] = '登陆成功啦'
            result['code'] = 200
            result['data'] = {}
            result['data']['token'] = token
            result['data']['userInfo'] = userModel.user

        else:
            result['massage'] = '登陆失败'
            result['status'] = 'error'
        return JsonResponse(result)
        
#获取左侧菜单列表
class MenusModel(View):
    def get(self, request):
        try:
            menuinfo = Menu.objects.all()
            menulist = []
            for i in menuinfo:
                print(i)
                menulist.append(
                    {
                        "id": i.id,
                        'name': i.name,
                        'path': i.path,
                        'component': i.component,
                        'children': list(i.children.values()),
                        'meta': {
                            'title': i.title,
                            'icon': i.icon,
                            'type': i.type,
                            'affix': i.affix,
                            'hidden':i.hidden
                        }
                    }
                )
            return JsonResponse({
                'code': 200,
                'message': '获取菜单信息成功',
                'data': menulist
            }, safe=False)
        except:
            return JsonResponse({
                'code': 400,
                'message': '获取菜单信息失败'
            })

# 岗位表视图
class PostView(ModelViewSet):
    queryset=Post.objects.all()
    serializer_class=PostSerializer

    @action(methods=['put'], detail=True)
    def edit(self, request, pk):
        return self.update(request, pk, partial=True)

#用户视图
class UserView(ModelViewSet):
    queryset=User.objects.all()
    serializer_class=UserSerializer

    @action(methods=['put'], detail=True)
    def edit(self, request, pk):
        return self.update(request, pk, partial=True)

#部门表视图
class DepartView(ModelViewSet):
    # queryset=Department.objects.all()
    queryset=Department.objects.filter(did__id=None)
    serializer_class=DepartSerializer

    @action(methods=['put'], detail=True)
    def edit(self, request, pk):
        return self.update(request, pk, partial=True)

# 权限视图
class PermissView(ModelViewSet):
    # queryset=Permission.objects.all()
    queryset=Permission.objects.filter(mid__id=None)
    serializer_class=PermissionSerializer

    @action(methods=['put'], detail=True)
    def edit(self, request, pk):
        return self.update(request, pk, partial=True)

# 角色视图
class RoleView(ModelViewSet):
    queryset=Role.objects.all()
    serializer_class=RoleSerializer

    @action(methods=['put'], detail=True)
    def edit(self, request, pk):
        return self.update(request, pk, partial=True)